<template>
  <div class="sale-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-header">
        <div class="header-left">
          <i class="el-icon-search"></i>
          <span>搜索条件</span>
        </div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增订单</el-button>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.order_number" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customer_name" placeholder="请输入客户姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="车辆型号">
          <el-input v-model="searchForm.vehicle_model" placeholder="请输入车辆型号" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.order_status" placeholder="请选择" clearable>
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

        <!-- 列表区域样式优化 -->
        <div class="table-container">
      <div class="table-header">
        <i class="el-icon-tickets"></i>
        <span>订单列表</span>
      </div>
    <!-- 订单列表 -->
    <el-table
  :data="orderList"
  border
  style="width: 100%"
  :header-cell-style="{
    background: '#f5f7fa',
    color: '#606266',
    height: '50px',
    fontWeight: '500'
  }"
  :cell-style="{
    padding: '12px 0'
  }"
  class="custom-table">
      <el-table-column prop="order_number" label="订单号" width="180"></el-table-column>
      <el-table-column prop="customer_name" label="客户姓名" width="150"></el-table-column>
      <el-table-column prop="vehicle_model" label="车辆型号" width="150"></el-table-column>
      <el-table-column prop="order_status" label="订单状态" width="120">
        <template slot-scope="{row}">
          <el-tag :type="getOrderStatusType(row.order_status)">
            {{ getOrderStatusText(row.order_status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="order_time" label="下单时间" width="180">
        <template slot-scope="{row}">
          {{ (row.order_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="payment_status" label="支付情况" width="120">
        <template slot-scope="{row}">
          <el-tag :type="getPaymentStatusType(row.payment_status)">
            {{ getPaymentStatusText(row.payment_status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="{row}">
        <el-button type="text" @click="viewDetail(row)">查看</el-button>
        <el-button type="text" @click="handleEdit(row)">编辑</el-button>
        <el-button type="text" @click="handleDelete(row)" class="delete-btn">删除</el-button>
      </template>
    </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
    </div>


    <!-- 详情弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="detailVisible"
      width="700px">
      <div v-if="currentDetail" class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentDetail.order_number }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentDetail.customer_name }}</el-descriptions-item>
          <el-descriptions-item label="车辆型号">{{ currentDetail.vehicle_model }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentDetail.order_status)">
              {{ getOrderStatusText(currentDetail.order_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ (currentDetail.order_time) }}
          </el-descriptions-item>
          <el-descriptions-item label="支付情况">
            <el-tag :type="getPaymentStatusType(currentDetail.payment_status)">
              {{ getPaymentStatusText(currentDetail.payment_status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-price" v-if="currentDetail.orderDetail">
          <h3>价格信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单价格">
              ¥ {{ currentDetail.orderDetail.price }}
            </el-descriptions-item>
            <el-descriptions-item label="优惠金额">
              ¥ {{ currentDetail.orderDetail.favorable_price }}
            </el-descriptions-item>
            <el-descriptions-item label="实付金额">
              ¥ {{ currentDetail.orderDetail.price - currentDetail.orderDetail.favorable_price }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-config" v-if="currentDetail.orderDetail">
          <h3>车辆配置</h3>
          <div class="config-content">{{ currentDetail.orderDetail.car_detail }}</div>
        </div>
      </div>
    </el-dialog>

    <!-- 状态更新弹窗 -->
    <el-dialog
      title="更新订单状态"
      :visible.sync="statusDialogVisible"
      width="400px">
      <el-form :model="statusForm">
        <el-form-item label="订单状态">
          <el-select v-model="statusForm.order_status" placeholder="请选择">
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateStatus">确定</el-button>
      </div>
    </el-dialog>



    <!-- 添加编辑订单弹窗 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增订单' : '编辑订单'"
      :visible.sync="editDialogVisible"
      width="800px">
      <el-form :model="orderForm" :rules="orderRules" ref="orderForm" label-width="100px">
        <el-form-item label="客户姓名" prop="customer_name">
          <el-input v-model="orderForm.customer_name" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        <el-form-item label="车辆型号" prop="vehicle_model">
          <!-- <el-input v-model="orderForm.vehicle_model" placeholder="请输入车辆型号"></el-input> -->
          <el-select v-model="orderForm.vehicle_model" placeholder="请选择车辆型号" style="width: 100%">
            <el-option
              v-for="model in carModelList"
              :key="model"
              :label="model"
              :value="model">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="order_status">
          <el-select v-model="orderForm.order_status" placeholder="请选择订单状态">
            <el-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付情况" prop="payment_status">
          <el-select v-model="orderForm.payment_status" placeholder="请选择支付状态">
            <el-option
              v-for="(value, key) in paymentStatusMap"
              :key="key"
              :label="value.text"
              :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单价格" prop="price">
          <el-input-number v-model="orderForm.price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="优惠金额" prop="favorable_price">
          <el-input-number v-model="orderForm.favorable_price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="车辆配置" prop="car_detail">
          <el-input type="textarea" v-model="orderForm.car_detail" rows="4" placeholder="请输入车辆配置详情"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOrder">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, getOrderDetail, updateOrderStatus, addOrder, editOrder, deleteOrder } from '@/api/sale/order'
import { getCarModelList } from '@/api/car/vehicle'

export default {
  name: 'saleOrderList',
  data() {
    return {
      carModelList:[],
      // 搜索表单
      searchForm: {
        order_number: '',
        customer_name: '',
        vehicle_model: '',
        order_status: ''
      },
      // 订单列表
      orderList: [],
      // 分页信息
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      // 详情弹窗
      detailVisible: false,
      currentDetail: null,
      // 状态更新弹窗
      statusDialogVisible: false,
      statusForm: {
        id: null,
        order_status: ''
      },
      // 订单状态选项
      orderStatusOptions: [
        { value: 'pending', label: '待处理' },
        { value: 'processing', label: '处理中' },
        { value: 'completed', label: '已完成' },
        { value: 'cancelled', label: '已取消' }
      ],
      // 支付状态映射
      paymentStatusMap: {
        unpaid: { text: '未支付', type: 'danger' },
        partial: { text: '部分支付', type: 'warning' },
        paid: { text: '已支付', type: 'success' }
      },
      editDialogVisible: false,
      dialogType: 'add', // add 或 edit
      orderForm: {
        customer_name: '',
        vehicle_model: '',
        order_status: '',
        payment_status: '',
        price: 0,
        favorable_price: 0,
        car_detail: ''
      },
      // 表单验证规则
      orderRules: {
        customer_name: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        vehicle_model: [
          { required: true, message: '请输入车辆型号', trigger: 'blur' }
        ],
        order_status: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ],
        payment_status: [
          { required: true, message: '请选择支付状态', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入订单价格', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchOrderList()
  },
  mounted() {
    this.getCarModelData()
  },
  methods: {
    //车辆型号集合
    getCarModelData(){
      getCarModelList().then(res => {
        console.log(res);
        if(res.data && res.data.length !== 0){
          this.carModelList = res.data.map(item => item.model);
          console.log(this.carModelList)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取订单列表
    async fetchOrderList() {
      try {
        const params = {
          ...this.searchForm,
          page: this.page.current,
          size: this.page.size
        }
        const res = await getOrderList(params)
        if (res.code === 1) {
          this.orderList = res.data;
          this.page.total = res.total;
        }
      } catch (error) {
        this.$message.error('获取订单列表失败')
      }
    },

    // 查看订单详情
    async viewDetail(row) {
      try {
        const res = await getOrderDetail({ id: row.id })
        if (res.code === 1) {
          this.currentDetail = {
            ...row,
            orderDetail: res.data[0]
          }
          this.detailVisible = true
        }
      } catch (error) {
        this.$message.error('获取订单详情失败')
      }
    },

    // 处理更新状态
    handleUpdateStatus(row) {
      this.statusForm.id = row.id
      this.statusForm.order_status = row.order_status
      this.statusDialogVisible = true
    },

    // 确认更新状态
    async confirmUpdateStatus() {
      try {
        const res = await updateOrderStatus(this.statusForm)
        if (res.code === 1) {
          this.$message.success('状态更新成功')
          this.statusDialogVisible = false
          this.fetchOrderList()
        }
      } catch (error) {
        this.$message.error('状态更新失败')
      }
    },

    // 搜索处理
    handleSearch() {
      this.page.current = 1
      this.fetchOrderList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        order_number: '',
        customer_name: '',
        vehicle_model: '',
        order_status: ''
      }
      this.handleSearch()
    },

    // 分页处理
    handleSizeChange(val) {
      this.page.size = val
      this.fetchOrderList()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.fetchOrderList()
    },


    // 获取订单状态显示文本
    getOrderStatusText(status) {
      const option = this.orderStatusOptions.find(item => item.value === status)
      return option ? option.label : status
    },

    // 获取订单状态类型
    getOrderStatusType(status) {
      const typeMap = {
        pending: 'warning',
        processing: 'primary',
        completed: 'success',
        cancelled: 'info'
      }
      return typeMap[status] || 'info'
    },

    // 获取支付状态显示文本
    getPaymentStatusText(status) {
      return this.paymentStatusMap[status]?.text || status
    },

    // 获取支付状态类型
    getPaymentStatusType(status) {
      return this.paymentStatusMap[status]?.type || 'info'
    },
    // 处理新增订单
    handleAdd() {
      this.dialogType = 'add'
      this.orderForm = {
        customer_name: '',
        vehicle_model: '',
        order_status: 'pending',
        payment_status: 'unpaid',
        price: 0,
        favorable_price: 0,
        car_detail: ''
      }
      this.editDialogVisible = true
    },

    // 处理编辑订单
    handleEdit(row) {
      try {
        const res = getOrderDetail({ id: row.id })
            .then(res => {
              if (res.code === 1) {
                this.currentDetail = {
                  ...row,
                  orderDetail: res.data[0]
                }
              }

              this.dialogType = 'edit'
              let tempDetail = res.data[0];
              this.orderForm = {
                id: row.id,
                customer_name: row.customer_name,
                vehicle_model: row.vehicle_model,
                order_status: row.order_status,
                payment_status: row.payment_status,
                price: tempDetail?.price || 0,
                favorable_price: tempDetail?.favorable_price || 0,
                car_detail: tempDetail?.car_detail || ''
              }
              this.editDialogVisible = true
            })
      } catch (error) {
        this.$message.error('获取订单详情失败')
      }


    },

    // 提交订单
    async submitOrder() {
      try {
        await this.$refs.orderForm.validate()
        if(this.dialogType === 'add'){
           const res = await addOrder(this.orderForm);
          if (res.code === 1) {
            this.$message.success(this.dialogType === 'add' ? '添加成功' : '编辑成功')
            this.editDialogVisible = false
            await this.fetchOrderList()
          }
        }else {
          console.log(this.orderForm)
           const res =await editOrder(this.orderForm);
          if (res.code === 1) {
            this.$message.success(this.dialogType === 'add' ? '添加成功' : '编辑成功')
            this.editDialogVisible = false
            await this.fetchOrderList()
          }
        }
      } catch (error) {
        console.error(error)
        this.$message.error('操作失败')
      }
    },

    // 处理删除订单
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该订单吗？', '提示', {
          type: 'warning'
        })

        const res = await deleteOrder({ id: row.id })
        if (res.code === 1) {
          this.$message.success('删除成功')
          this.fetchOrderList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.sale-container {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f0f2f5;

  .search-area {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;

    .search-header {
      padding: 15px 20px;
      border-bottom: 1px solid #ebeef5;
      display: flex;

      .header-left{
        display: flex;
        align-items: center;
        margin-right: 20px;;
      }

      i {
        color: #409EFF;
        margin-right: 8px;
        font-size: 18px;
      }

      span {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .search-form {
      padding: 20px;

      .el-form-item {
        margin-bottom: 0;
        margin-right: 20px;

        .el-input {
          width: 220px;
        }
      }
    }
  }

  .table-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .custom-table {
      width: 100%;
      // 表格内边距
      padding: 20px;

      // 去除表格边框
      &::before {
        display: none;
      }

      // 表格行样式
      ::v-deep .el-table__row {
        &:hover {
          // 鼠标悬浮效果
          background-color: #f5f7fa !important;
          td {
            background-color: transparent;
          }
        }
      }

      // 单元格样式
      ::v-deep .el-table__cell {
        // 垂直居中
        .cell {
          padding: 0 12px;
          line-height: 23px;
          color: #606266;
        }
      }

      // 表头样式
      ::v-deep .el-table__header {
        th {
          background-color: #f5f7fa !important;
          &.is-leaf {
            border-bottom: 1px solid #EBEEF5;
          }
        }
      }
      ::v-deep .el-table__body {
        //width: 100%;
      }

      // 表格边框颜色
      ::v-deep td, ::v-deep th {
        border-color: #EBEEF5;
      }

      // 斑马纹样式
      ::v-deep .el-table__row--striped {
        td {
          background-color: #FAFAFA;
        }
      }

      // 操作列按钮样式
      .el-button--text {
        position: relative;
        padding: 0 8px;
        font-size: 13px;
        color: #409EFF;

        &:hover {
          color: #66b1ff;
        }

        & + .el-button--text {
          margin-left: 8px;

          &::before {
            content: '';
            position: absolute;
            left: -4px;
            top: 50%;
            transform: translateY(-50%);
            width: 1px;
            height: 12px;
            background-color: #DCDFE6;
          }
        }
      }

      // 状态标签样式优化
      .el-tag {
        border-radius: 12px;
        padding: 0 12px;
        height: 24px;
        line-height: 22px;
        border-width: 1px;

        &--success {
          background-color: #f0f9eb;
        }
        &--warning {
          background-color: #fdf6ec;
        }
        &--danger {
          background-color: #fef0f0;
        }
        &--info {
          background-color: #f4f4f5;
        }
      }
    }

    .table-header {
      padding: 15px 20px;
      border-bottom: 1px solid #ebeef5;

      i {
        color: #409EFF;
        margin-right: 8px;
        font-size: 18px;
      }

      span {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .el-table {
      width: 100%;
      padding: 20px;

      &::before {
        display: none;
      }

      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    padding: 10px 20px;
    text-align: right;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  // 详情弹窗样式优化
  .detail-container {
    .el-descriptions {
      padding: 20px;
      background-color: #fafafa;
      border-radius: 4px;
    }

    .detail-price,
    .detail-config {
      margin-top: 25px;

      h3 {
        position: relative;
        margin-bottom: 20px;
        padding-left: 12px;
        font-size: 16px;
        font-weight: 500;
        color: #303133;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background-color: #409EFF;
          border-radius: 2px;
        }
      }
    }

    .config-content {
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;
      line-height: 1.8;
      color: #606266;
      font-size: 14px;
    }
  }

  // 状态标签样式优化
  .el-tag {
    padding: 0 12px;
    height: 24px;
    line-height: 22px;
  }

  // 操作按钮样式优化
  .el-button--text {
    padding: 0 8px;
    font-size: 13px;

    & + .el-button--text {
      margin-left: 8px;
    }
  }
}

// 弹窗样式优化
::v-deep .el-dialog {
  border-radius: 8px;
  overflow: hidden;

  .el-dialog__header {
    padding: 20px;
    background-color: #f5f7fa;
    margin-right: 0;
    border-bottom: 1px solid #ebeef5;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 25px;
  }

  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
  }
}
</style>
